<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { get_upload } from '../../api/index'
import appData from "@/utils/emoji"
// 定义用户信息
const userInfo = ref({
  userId: ''
})
// 定义输入框中的消息
const yourMessage = ref('')
// 定义消息列表
const messageList = ref([])
// 定义在线用户列表
const onlineList = ref([])
// 定义websocket对象
let ws = null
// 发送消息函数
const sendMessage = () => {
  // 如果输入框中有消息，则发送消息
  if (yourMessage.value) {
    ws.send(
      JSON.stringify({
        type: 'message',
        userId: userInfo.value.userId,
        content: yourMessage.value
      })
    )
    // 清空输入框
    yourMessage.value = ''
  }
}

const initWebsocket = () => {
  ws = new WebSocket('ws://120.46.35.214:8080/')
  // 创建websocket对象
  console.log(ws)
  ws.onopen = () => {
    // websocket连接成功时触发
    console.log('websocket连接成功')
    ws.send(
      // 发送初始化消息
      JSON.stringify({
        type: 'init',
        userId: userInfo.value.userId,
        content: '欢迎来到聊天室'
      })
    )
  }
  ws.onerror = () => {
    // websocket连接失败时触发
    console.log('websocket连接失败')
  }
  ws.onmessage = (data) => {
    // 接收到消息时触发
    const message = JSON.parse(data.data)
    const images = JSON.parse(data.data)
    // 解析消息
    switch (message.type) {
      // 根据消息类型进行处理
      case 'tips':
        console.log(message.content)
        break
      case 'message':
        setTimeout(() => {
          // 滚动到底部
          nextTick(() => {
            const chatRoom = document.querySelector('.chat-room')
            chatRoom.scrollTop = chatRoom.scrollHeight
          })
        }, 500)

        messageList.value.push(message)
        // 将消息添加到消息列表
       
        break
      case 'image':
        messageList.value.push(images)
        break
      case 'onlineList':
        onlineList.value = message.list
        // 更新在线用户列表
        break

      default:
        break
    }
  }
  ws.onclose = () => {
    // websocket连接关闭时触发
    console.log('websocket连接关闭')
  }
}

const user=JSON.parse(localStorage.getItem('user'))
onMounted(() => {
  // 组件挂载时触发
  userInfo.value.userId = user.avatar
  // 生成用户ID
  initWebsocket()
  // 初始化websocket
})
const inputs = ref('')
let url = ref('');
const upload = async () => {
  let file = inputs.value.files[0];
  let data = new FormData();
  data.append('file', file)
  let res = await get_upload(data)
  if (res.data.code == 200) {
    alert('上传成功')
    url.value = res.data.result
    ws.send(
      JSON.stringify({
        type: 'message',
        userId: userInfo.value.userId,
        content: url.value
      })
    )
  } else {
    alert('上传失败')
  }
}
// 循环获取表情包下标并赋值到输入框内
const faceList=ref([])
const emojiItem=ref('')
const download = async () => {
  for (let i in appData) {
    faceList.value.push(appData[i].char);
  }
}
download()
// 点击表情按钮加到输入框中
const getEmo=async(index)=>{
  emojiItem.value = index
  let emojis = Object.keys(appData).map(key => appData[key].char);
  yourMessage.value += emojis[index];
}
localStorage.setItem('messageList', JSON.stringify(messageList.value))
// 遮罩层状态
const show=ref(false)
</script>
<template>
  <div class="app">
    <h2> 在线人数{{ onlineList.length }}</h2>
    <div class="chat-room">
      <div class="message-item" v-for="(item, index) in messageList" :key="index">
        <div class="flex-left" v-if="item.userId !== userInfo.userId">
          <div class="avatar">
                <img :src="item.userId" alt="">
          </div>
          <div style="margin-left: 10px" class="message-content">
            <p v-if="item.content.indexOf('http') == -1">{{ item.content }}</p>
            <img v-else-if="item.content.indexOf('jpg', 'png', 'gif', 'jpeg') !== -1" :src="item.content" alt=""
              style="width: 150px; height: 100px;">
            <video v-else controls autoplay loop muted preload="auto" :src=item.content
              style="width: 150px; height: 100px;"></video>
          </div>
        </div>
        <div v-else class="flex-right">
          <div class="message-content" style="margin-right: 10px; background-color: #ccc;">
            <p v-if="item.content.indexOf('http') == -1" >{{ item.content }}</p>
            <img v-else-if="item.content.indexOf('jpg', 'png', 'gif', 'jpeg') !== -1" :src="item.content" alt=""
              style="width: 150px; height: 100px;">
            <video v-else controls autoplay loop muted preload="auto" :src=item.content
              style="width: 150px; height: 100px;"></video>
          </div>
          <div class="avatar">
              <img :src="item.userId" alt="">
          </div>
        </div>
      </div>
    </div>
    <div class="main">
      <input class="message-input" type="text" v-model="yourMessage" @keyup.enter="sendMessage" />
      <button class="send-btn" @click="sendMessage">发送</button>
    </div>
    <div class="send-box1">
      <div class="send-box1_2">
        <van-icon name="smile" @click="show = !show" />
        <div v-if="show" class="emotionList">
          <a href="javascript:void(0)" @click="getEmo(index)" v-for="(item, index) in faceList" :key="index"
            class="emotionItem">{{ item }}</a>
        </div>
      </div>
      <div class="send-box1_1">
        发送图片
        <input type="file" ref="inputs" @change="upload" />
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.app {
  width: 100%;
  display: grid;
  font-size: 0.3rem;
  background-color: #fff;
  position: fixed;

  h2 {
    width: 100%;
    height: 30px;
    text-align: center;
    line-height: 30px;
    border-bottom: 1px solid #ccc;
  }
}

.chat-room {
  overflow: auto;
  height: 480px;
  padding: 20px 0;
  height: 80vh;
  background-color: #f3f3f3;
}

.message-item {
  width: 80%;
  margin: 0 auto;
  margin-bottom: 15px;
}

.flex-left {
  display: flex;
  justify-content: flex-start;
}

.flex-right {
  display: flex;
  justify-content: flex-end;
}

.avatar {
  width: 50px;
  height: 50px;
  line-height: 50px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #fff;
  font-size: 15px;
  text-align: center;
  img{
    width: 50px;
    height: 50px;
  }
}

.message-content {
  background: rgb(6, 255, 172);
  border-radius: 8px;
  padding: 10px;
  font-size: 16px;
  width: 150px;
  P{
    // 自动换行
    word-wrap: break-word;
    word-break: break-all;
  }
}

.main {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 40px;
  border-radius: 5px;
  overflow: hidden;

  .message-input {
    width: 80%;
    height: 100%;
    border: none;
    outline: none;
    padding: 0 10px;
    font-size: 16px;
  }

  .send-btn {
    width: 20%;
    height: 100%;
    border: none;
  }
}

.send-box1 {
  width: 100%;
  height: 40px;
  background-color: #fff;
  border-bottom: 1px solid #ccc;
  display: flex;
  position: fixed;
  left: 0;
  bottom: 104px;

  .send-box1_1 {
    display: flex;
    width: 85px;
    height: 35px;
    font-size: 12px;
    color: red;
    overflow: hidden;
    align-items: center;
    justify-content: space-around;
    border-radius: 10px;
    border: none;
    border: 1px solid #000;
    flex-wrap: wrap;
    margin-left: 20px;

    input {
      width: 100%;
      opacity: 0;
    }
  }

  .send-box1_2 {
    width: 35px;
    height: 35px;
    font-size: 35px;
    position: relative;
    margin-left: 10px;

    .emotionList {
      width: 375px;
      height: 105px;
      background-color: rgb(198, 240, 226);
      position: absolute;
      overflow: auto;
      top: -110px;
      left: -10px;
      font-size: 25px;
      display: flex;
      flex-wrap: wrap;
      a{
        margin-left: 15px;
      }
    }
  }
}

.main {
  bottom: 65px;
  width: 100%;
  height: 40px;
  border-radius: 5px;
  overflow: hidden;
  position: fixed;

  .message-input {
    width: 77%;
    height: 40px;
    font-size: 20px;
    padding: 3px;
    border-radius: 10px;
    border: 1px solid #ccc;
  }

  .send-btn {
    width: 65px;
    right: 5px;
    bottom: 5px;
    height: 40px;
    font-size: 16px;
    background: #219fe8;
    color: #fff;
    border: none;
    border-radius: 5px;
    margin-left: 10px;
  }
}
</style>